package com.ai.WS;

import org.json.JSONException;
import org.json.JSONObject;

import android.os.AsyncTask;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;

import com.ai.util.ConserveActivity;

public class ConserveWSTask extends AsyncTask<String, Integer, String> {

	private ConserveActivity activity;
	private static final String debugTag = "PROBLEMA";
	private ProgressBar progressBar;
	private ConserveWS.metodos metodo;

	/**
	 * Construct a task
	 * 
	 * @param activity
	 */
	public ConserveWSTask(ConserveActivity activity, ConserveWS.metodos metodo) {
		super();
		this.activity = activity;
		this.metodo = metodo;
	}

	public ConserveWSTask(ConserveActivity activity, ConserveWS.metodos metodo,
			ProgressBar progressBar) {
		super();
		this.activity = activity;
		this.metodo = metodo;
		this.progressBar = progressBar;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();

	}

	@Override
	protected String doInBackground(String... params) {
		try {

			String result = "Entrou em nada!";
			if (metodo == ConserveWS.metodos.login)
				result = ConserveWS.login(params);
			else if (metodo == ConserveWS.metodos.GetCategorys) {
				result = ConserveWS.getCategorys(params);
			} else if (metodo == ConserveWS.metodos.Singup)
				result = ConserveWS.signUP(params);
			else if (metodo == ConserveWS.metodos.NovoPoint)
				result = ConserveWS.novoPoint(params);
			else if (metodo == ConserveWS.metodos.GetPoints)
				result = ConserveWS.getPoints(params);
			else if(metodo== ConserveWS.metodos.GetComentarios)
				result = ConserveWS.listarPointConserveComentario(params);
			else if(metodo== ConserveWS.metodos.NovoApoio)
				result = ConserveWS.novoApoio(params);
			else if(metodo== ConserveWS.metodos.NovoComentario)
				result = ConserveWS.novoComentario(params);
			return result;
		} catch (Exception e) {
			Log.d("PROBLEMA"," retorno do metodo"+ e.getMessage());
			return new String();
		}
	}

	@Override
	protected void onPostExecute(String result) {

		if (result.length() == 0) {
			Log.d(debugTag, "Retornou nada!");
			return;
		}

		try {
			JSONObject respObj = new JSONObject(result);
			respObj = new JSONObject(respObj.getString("d"));
			activity.retornoWS(respObj);
		} catch (JSONException e) {
			Log.d(debugTag, result);
		}
		if (progressBar != null)
			progressBar.setVisibility(View.INVISIBLE);
	}
}
